package com.ocom.payconfig.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.entity.payconfig.EntityXfMerchMoneyDay;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.request.exposeapi.boczhxy.AuthenticationRequest;
import com.ocom.common.request.exposeapi.boczhxy.TranInfo;
import com.ocom.common.request.payconfig.ConsMerchPayReportsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payconfig.dao.IDXfMerchMoneyDay;
import com.ocom.payconfig.service.XfMerchMoneyDayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class XfMerchMoneyDayServiceImpl extends ServiceImpl<IDXfMerchMoneyDay, EntityXfMerchMoneyDay> implements XfMerchMoneyDayService {

    @Autowired
    XfMerchMoneyDayService xfMerchMoneyDayService;

    @Autowired
    IDXfMerchMoneyDay idXfMerchMoneyDay;

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityXfMerchMoneyDay> getXfMerchMoneyDayByPayDate(Long comId, String payDate) {

        return xfMerchMoneyDayService.list(new LambdaQueryWrapper<EntityXfMerchMoneyDay>()
                .eq(EntityXfMerchMoneyDay::getComId, comId)
                .eq(EntityXfMerchMoneyDay::getPayDate, payDate)
                .orderByAsc(EntityXfMerchMoneyDay::getMerchNo));
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityXfMerchMoneyDay> getXfMerchMoneyDayByPayDate2(Long comId, String payDate) {

        return xfMerchMoneyDayService.list(new LambdaQueryWrapper<EntityXfMerchMoneyDay>()
                .eq(EntityXfMerchMoneyDay::getComId, comId)
                .eq(EntityXfMerchMoneyDay::getPayState, 0)
                .eq(EntityXfMerchMoneyDay::getPayDate, payDate)
                .orderByAsc(EntityXfMerchMoneyDay::getMerchNo));
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public Result getMerchMoneyDayList(Long comId,ConsMerchPayReportsRequest consMerchPayReportsRequest) {

        if(consMerchPayReportsRequest.getBeginDate()==null || consMerchPayReportsRequest.getBeginDate().isEmpty()){
            LocalDate currentDate = LocalDate.now();
            LocalDate yesterday = currentDate.minusDays(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String yesterdayString = yesterday.format(formatter);
            consMerchPayReportsRequest.setBeginDate(yesterdayString);
        }

        if (ObjectUtil.isEmpty(consMerchPayReportsRequest.getPage())) {
            consMerchPayReportsRequest.setPage(1);
        }
        if (ObjectUtil.isEmpty(consMerchPayReportsRequest.getSize())) {
            consMerchPayReportsRequest.setSize(10);
        }
        PageHelper.startPage(consMerchPayReportsRequest.getPage(), consMerchPayReportsRequest.getSize());
        List<EntityXfMerchMoneyDay> merchMoneyDayList = idXfMerchMoneyDay.selectMerchMoneyDayList(consMerchPayReportsRequest);

        PageInfo<EntityXfMerchMoneyDay> pageInfo = new PageInfo<>(merchMoneyDayList);

        HashMap<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return ResultUtil.success(map);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
    public Result modifyMerchMoneyDay(Long comId,AuthenticationRequest authenticationRequest) {

        List<TranInfo> tranInfo = authenticationRequest.getTranInfo();
        tranInfo.forEach(tranInfo1 -> {
            LambdaUpdateWrapper<EntityXfMerchMoneyDay> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(EntityXfMerchMoneyDay::getNowReceipts, tranInfo1.getTranAmt())
                    .set(EntityXfMerchMoneyDay::getPayState, (tranInfo1.getRetCode().equals("0000000")||tranInfo1.getRetCode().equals("1000000")) ? 1 : 2)
                    .set(EntityXfMerchMoneyDay::getTraceNo, authenticationRequest.getTraceNo())
                    .set(EntityXfMerchMoneyDay::getTraceNoOut, authenticationRequest.getTraceNo())
                    .set(EntityXfMerchMoneyDay::getRetMsg, tranInfo1.getRetMsg())
                    .set(EntityXfMerchMoneyDay::getUpdateTime,new Date())
                    .eq(EntityXfMerchMoneyDay::getComId, authenticationRequest.getComId())
                    .eq(EntityXfMerchMoneyDay::getMerchNo, tranInfo1.getMerNo())
                    .eq(EntityXfMerchMoneyDay::getPayState, 0)
                    .eq(EntityXfMerchMoneyDay::getPayDate,authenticationRequest.getTranDate());
            try {
                xfMerchMoneyDayService.update(updateWrapper);
            } catch (Exception e) {
                log.info("更新失败:{}", e.getMessage());
                throw new RuntimeException(e);
            }
        });
        return ResultUtil.success();
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityXfMerchMoneyDay> recordOfArrears(Long comId, String payDate) {

        LambdaQueryWrapper<EntityXfMerchMoneyDay> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.
                eq(EntityXfMerchMoneyDay::getPayState, 0)
                .eq(EntityXfMerchMoneyDay::getComId, comId)
                .lt(EntityXfMerchMoneyDay::getNowReceived, 0)
                .eq(EntityXfMerchMoneyDay::getPayDate, payDate)
                .orderByAsc(EntityXfMerchMoneyDay::getMerchNo);
        return xfMerchMoneyDayService.list(queryWrapper);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public Boolean updateXfMerchMoneyDay(Integer id, String payDate) {

        LambdaUpdateWrapper<EntityXfMerchMoneyDay> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(EntityXfMerchMoneyDay::getRepairPayDate, payDate)
                .set(EntityXfMerchMoneyDay::getPayState, 3)
                .eq(EntityXfMerchMoneyDay::getId, id);
        return xfMerchMoneyDayService.update(updateWrapper);


    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.MASTER)
//    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public Boolean saveXfMerchMoneyDay(Long comId,EntityXfMerchMoneyDay entityXfMerchMoneyDay) {
        QueryWrapper<EntityXfMerchMoneyDay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("com_id", comId);
        queryWrapper.eq("merch_no", entityXfMerchMoneyDay.getMerchNo());
        queryWrapper.eq("pay_date", entityXfMerchMoneyDay.getPayDate());
        Integer count = this.count(queryWrapper);
        if (count > 0) return true;
        return xfMerchMoneyDayService.save(entityXfMerchMoneyDay);
    }

}